from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
import os

""" 
CBC 密码分组链接模式, 要使用初始化向量 IV 以增强安全性。
"""

def des_encrypt(data, key, iv):
    cipher = DES.new(key, DES.MODE_CBC, iv)
    ciphertext = cipher.encrypt(pad(data.encode("utf-8"), DES.block_size))
    return ciphertext


def des_decrypt(ciphertext, key, iv):
    cipher = DES.new(key, DES.MODE_CBC, iv)
    plaintext = unpad(cipher.decrypt(ciphertext), DES.block_size)
    return plaintext.decode("utf-8")


# 示例
# key = os.urandom(8)  # 生成一个8字节的随机密钥
key = b"12345678"  # 固定密钥
iv = os.urandom(8)  # 生成一个8字节的随机初始化向量
data = "hello world"  # 原始数据

# 加密
cipher_text = des_encrypt(data, key, iv)
print("Encrypted:", cipher_text.hex())

# 解密
plain_text = des_decrypt(cipher_text, key, iv)
print("Decrypted:", plain_text)

